import { Text, StyleSheet, View, Dimensions, TextInput, SafeAreaView, ScrollView, Image, TouchableWithoutFeedback, Pressable, Clipboard } from 'react-native'
import React, { Component, useState, useRef } from 'react'
import { connect } from 'react-redux'
import { pTx } from "../../utils/dimensions"
import { popularDapp, BSCDapp } from "../../utils/browserDapp"
import { Toast, SwipeCell } from '@pingtou/rn-vant';
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import Realm from "realm"
import IconFont from '@pingtou/rn-vant-icons'

const Browsers = (props) => {
    const swipeCellRefs = useRef()
    const [web3ViewUrl, setWeb3ViewUrl] = useState("")
    const realm = useRealm();
    const browserSearchLogs = useQuery(schemaName.BrowserSearchLogs).sorted('time', true)

    onSubmit = () => {
        var domain = web3ViewUrl.split('/')
        var domainUrl = ['https:', 'http:'].indexOf(domain[0]) !== -1 ? web3ViewUrl : 'https://' + web3ViewUrl
        console.log(domainUrl, "1111111111111111")
        props.navigation.navigate('web3View', { url: domainUrl })
        const list = browserSearchLogs.filtered(`url == '${domainUrl}'`)
        if (list.length == 0) {
            realm.write(() => {
                realm.create(schemaName.BrowserSearchLogs, {
                    _id: new Realm.BSON.UUID(),
                    url: domainUrl,
                    time: Date.parse(new Date()) / 1000,
                }, true)
            })
        } else {
            realm.write(() => {
                realm.create(schemaName.BrowserSearchLogs, {
                    ...list[0],
                    time: Date.parse(new Date()) / 1000,
                }, true)
            })
        }
    }
    onToSubmit = (item) => {
        props.navigation.navigate('web3View', { url: item.url })
        realm.write(() => {
            realm.create(schemaName.BrowserSearchLogs, {
                ...item,
                time: Date.parse(new Date()) / 1000,
            }, true)
        })
    }
    clear = () => {
        realm.write(() => {
            realm.delete(browserSearchLogs);
        })
    }
    deleteItem = (item) => {
        swipeCellRefs[item._id + ""]?.close()
        setTimeout(() => {
            realm.write(() => {
                realm.delete(item)
            })
        }, 200)

    }
    return (
        <SafeAreaView style={styles.container}>
            <View style={styles.headSearch}>
                <View style={styles.search}>
                    <IconFont name="search" size={pTx(24)} color={"rgba(175, 181, 189, 1)"} />
                    <TextInput
                        blurOnSubmit={true}
                        value={web3ViewUrl}
                        style={styles.input}
                        onChangeText={value => setWeb3ViewUrl(value)}
                        onSubmitEditing={this.onSubmit}
                        placeholder='搜索DApp或输入链接进入玩耍'
                    />
                </View>
                <Text style={styles.cancel} onPress={() => props.navigation.goBack()}>取消</Text>
            </View>
            {web3ViewUrl ?
                <TouchableWithoutFeedback onPress={this.onSubmit}>
                    <View style={styles.goto}>
                        <Text style={styles.gotoText}>前往Dapp:</Text>
                        <Text style={styles.gotoLink} ellipsizeMode={'tail'} numberOfLines={1}>{web3ViewUrl}</Text>
                    </View>
                </TouchableWithoutFeedback>
                :
                <View style={styles.page}>

                    <ScrollView style={styles.scrollView}>
                        <View style={styles.popular}>
                            <View style={styles.title}>
                                <View style={styles.titleInfo}>
                                    <Image resizeMode="contain" style={styles.titleIcon} source={require('../../assets/image/icon38.png')}></Image>
                                    <Text style={styles.titleText}> 热门搜索</Text>
                                </View>
                            </View>
                            <View style={styles.popularRow}>
                                {popularDapp.map((item, index) => {
                                    return index < 6 && <Text style={styles.popularCell} onPress={() => props.navigation.navigate('web3View', { url: item.url, title: item.title })} key={index}>{item.title}</Text>
                                })}
                            </View>
                        </View>
                        <View style={styles.history}>
                            <View style={[styles.title, { borderBottomWidth: 1, paddingBottom: pTx(8) }]}>
                                <View style={styles.titleInfo}>
                                    <Image resizeMode="contain" style={styles.titleIcon} source={require('../../assets/image/icon39.png')}></Image>
                                    <Text style={styles.titleText}>历史记录</Text>
                                </View>
                                <TouchableWithoutFeedback onPress={this.clear}>
                                    <Image resizeMode="contain" style={styles.titleIcon} source={require('../../assets/image/delete.png')}></Image>
                                </TouchableWithoutFeedback>
                            </View>
                            <View style={styles.historyRow}>
                                {browserSearchLogs.map((item, index) => {
                                    return <SwipeCell ref={(ref) => {
                                        if (ref) swipeCellRefs[item._id + ""] = ref;
                                    }} key={index} rightAction={
                                        <View style={styles.deleteLinkButton}>
                                            <Text style={styles.deleteLink} onPress={() => this.deleteItem(item)}>删除</Text>
                                        </View>
                                    }><Pressable onPress={() => this.onToSubmit(item)} onLongPress={() => {
                                        Clipboard.setString(item.url)
                                        Toast(item.url + " 已复制")
                                    }} key={index}>
                                            <View style={styles.historyCell} >
                                                {
                                                    item.icon ?
                                                        <Image resizeMode="contain" style={styles.historyImage} defaultSource={require('../../assets/image/icon40.png')} source={{ uri: item.icon }}></Image>
                                                        :
                                                        <Image resizeMode="contain" style={styles.historyImage} source={require('../../assets/image/icon40.png')}></Image>

                                                }
                                                <View style={styles.historyInfo}>
                                                    <Text style={styles.historyCellName} selectable={true}>{item.title || '网页无法打开'}</Text>
                                                    <Text style={styles.historyCellLink} ellipsizeMode={'tail'} numberOfLines={1}>{item.url}</Text>
                                                </View>
                                            </View>
                                        </Pressable>
                                    </SwipeCell>
                                })}
                            </View>
                        </View>
                    </ScrollView>
                </View>
            }
        </SafeAreaView>
    )
}
const mapStateToProps = (state) => state.dapp
const mapDispatchToProps = {
}
export default connect(mapStateToProps, mapDispatchToProps)(Browsers)


const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    headSearch: {
        flexDirection: "row",
        alignItems: "center",
        paddingHorizontal: pTx(15),
        marginVertical: pTx(10),
    },
    search: {
        flex: 1,
        flexDirection: "row",
        alignItems: "center",
        paddingHorizontal: pTx(12),
        backgroundColor: "#fff",
        borderRadius: pTx(6),
    },
    input: {
        flex: 1,
        height: pTx(32),
        padding: 0,
        paddingLeft: pTx(5),
    },
    cancel: {
        paddingLeft: pTx(16),
        fontSize: pTx(16),
        color: "rgba(10, 12, 20, 1)"
    },
    page: {
        flex: 1,
        backgroundColor: "#fff"
    },
    scrollView: {
        paddingHorizontal: pTx(15),
    },
    title: {
        marginTop: pTx(20),
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        borderBottomColor: "rgba(175, 181, 189, 0.15)"
    },
    titleInfo: {
        flexDirection: "row",
        alignItems: "center",
    },
    titleIcon: {
        width: pTx(16),
        height: pTx(16),
        marginRight: pTx(8),
    },
    titleText: {
        fontSize: pTx(16),
        color: "rgba(175, 181, 189, 1)"
    },
    popularRow: {
        paddingBottom: pTx(12),
        flexWrap: "wrap",
        flexDirection: 'row',
    },
    popularCell: {
        marginRight: pTx(8),
        marginTop: pTx(8),
        paddingHorizontal: pTx(12),
        paddingVertical: pTx(8),
        backgroundColor: "rgba(237, 237, 237, 1)",
        borderRadius: pTx(5),
    },
    historyRow: {
        marginTop: pTx(12),
    },
    historyCell: {
        paddingBottom: pTx(12),
        marginBottom: pTx(12),
        flexDirection: 'row',
        alignItems: "flex-start",
        borderBottomWidth: 1,
        borderBottomColor: "rgba(175, 181, 189, 0.15)"
    },
    historyInfo: {
        marginLeft: pTx(12),
    },
    historyImage: {
        width: pTx(16),
        height: pTx(16),
        borderRadius: pTx(16),
    },
    historyCellName: {
        lineHeight: pTx(18),
        fontSize: pTx(16),
        color: "rgba(10, 12, 20, 1)",
        maxWidth: pTx(300),
    },
    historyCellLink: {
        // marginTop: pTx(2),
        fontSize: pTx(13),
        color: "rgba(175, 181, 189, 1)"
    },
    goto: {
        backgroundColor: "#fff",
        flexDirection: "row",
        alignItems: "center",
        paddingHorizontal: pTx(15),
        paddingVertical: pTx(10),
    },
    gotoText: {
        fontSize: pTx(14),
        color: "rgba(10, 12, 20, 1)"
    },
    gotoLink: {
        marginLeft: pTx(5),
        fontSize: pTx(14),
        color: "rgba(68, 225, 240, 1)"
    },
    deleteLinkButton: {
        flexDirection: 'row',
        alignItems: "center",
        justifyContent: "center",
        width: pTx(50),
        height: pTx(35),
        backgroundColor: "rgb(238, 10, 36)",
    },
    deleteLink: {
        color: "#fff",
        textAlign: "center"
    }
})